/* 
 * File:   DynamicLib.cpp
 * Author: dell
 * 
 * Created on 2012年4月4日, 下午1:44
 */

#include "DynamicLib.h"

namespace Rapid{
    static const char* libUninitialized = "dynamic lib uninitialized";
    static const char* libIsOpened= "dynamic lib already opened";

    DynamicLib::DynamicLib():
        handle(NULL),error(NULL)
    {
    }

    DynamicLib::~DynamicLib() {
        close();
    }

    bool DynamicLib::open(const char* lib, int mode /* = RTLD_NOW */){
        if (handle){
            error = libIsOpened;
            LOG_DEBUG(error);
            return false;
        }    
        handle = dlopen (lib, mode);     //打开argv[1]指定的动态库
        if (!handle){
            error = dlerror();
            LOG_DEBUG(error);
            return false;
        }
        return true;
    }

    void* DynamicLib::getMethod(const char* name){
        if (!handle){
            if(!error){
                error = libUninitialized;
            }
            LOG_DEBUG(error);
            return NULL;
        }
        dlerror();
        void* mpt = dlsym(handle,name); 
        if((error = dlerror())){
            LOG_DEBUG(error);
            return NULL;
        }
        error = NULL;
        return mpt;
    }


    void DynamicLib::close(){
        if (!handle){
            error = libUninitialized;
            LOG_DEBUG(error);
            return;
        }
        dlclose(handle); 
        error = dlerror();
        handle = NULL;
    }


}
